/*
 * Copyright (c) 2020-2099 the original author or authors. All rights reserve.
 */
package org.tianyun.cloud.datasource.sharding;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.util.CollectionUtils;
import org.tianyun.cloud.config.console.ConsoleBean;
import org.tianyun.cloud.datasource.configuration.HikariProperties;
import org.tianyun.cloud.datasource.configuration.ShardingDataSourceProperties;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Map;
import java.util.Properties;

/**
 * 分片数据源工厂
 *
 * @auther ebert_chan
 */
public class ShardingDataSourceFactory implements ConsoleBean, DisposableBean {

    private ShardingDataSourceProperties shardingDataSourceProperties;

    private DataSource delegate;

    public ShardingDataSourceFactory(ShardingDataSourceProperties shardingDataSourceProperties) throws SQLException {
        this.shardingDataSourceProperties = shardingDataSourceProperties;
        delegate = ShardingDataSourceBuilder.configure(shardingDataSourceProperties).build();
    }

    public DataSource getDelegate() {
        return delegate;
    }

    @Override
    public Properties startupArguments() {
        Properties properties = new Properties();
        if (CollectionUtils.isEmpty(shardingDataSourceProperties.getNodes())) {
            return properties;
        }

        for (Map.Entry<String, HikariProperties> entry : shardingDataSourceProperties.getNodes().entrySet()) {
            properties.put("sharding.nodes." + entry.getKey() + ".jdbc-url", entry.getValue().getJdbcUrl().substring(0, entry.getValue().getJdbcUrl().indexOf("?")));
        }

        return properties;
    }

    @Override
    public void destroy() throws Exception {
        if (this.delegate instanceof AutoCloseable) {
            ((AutoCloseable) this.delegate).close();
        }
    }

}
